package cn.tjad.tjad2.module.form.views;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.bruce.pickerview.popwindow.DatePickerPopWin;

import cn.tjad.tjad2.data.bean.FormDetail;
import cn.tjad.tjad2.utils.DatePickUtils;

import static android.util.TypedValue.COMPLEX_UNIT_SP;

public class DatePickView extends FormBaseLayout implements View.OnClickListener, DatePickerPopWin.OnDatePickedListener {

    private TextView textView;

    public DatePickView(Context context) {
        super(context);
    }

    public DatePickView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void init() {
        super.init();
        addTextView();
        setOnClickListener(this);
    }

    private void addTextView() {
        if (textView == null) {
            textView = new TextView(getContext());
            textView.setTextColor(Color.parseColor("#101010"));
            textView.setTextSize(COMPLEX_UNIT_SP, 14);
            textView.setGravity(Gravity.CENTER);
            textView.setEnabled(false);
//            textView.setText(texts);
        }
        if (textView.getParent() == null) {
            LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            this.addView(textView, lp);
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (enabled) {
            setOnClickListener(this);
        } else {
            setOnClickListener(null);
        }
    }

    @Override
    public void setFormStepDetail(FormDetail.FormStepDetail formStepDetail) {
        super.setFormStepDetail(formStepDetail);
        textView.setText(formStepDetail.value);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        DatePickUtils.showDatePicker(getContext(), textView.getText().toString(), this);

    }

    /**
     * Listener when date has been checked
     *
     * @param year
     * @param month
     * @param day
     * @param dateDesc yyyy-MM-dd
     */
    @Override
    public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
        textView.setText(dateDesc);
        formStepDetail.value = dateDesc;
        if (onEditListener != null) {
            onEditListener.onEdit(formStepDetail.detail.id, dateDesc);
        }
    }
}
